<?php
/**
 * Created by PhpStorm.
 * User: heqian
 * Date: 17-7-15
 * Time: 下午7:09
 */
class register extends \Swoole\App
{
    public $register_address = '127.0.0.1:1238';
    public $onWorkerStart = '';
    protected  function init_server()
    {
        if (!$this->_socketName) {
            return;
        }
        // Get the application layer communication protocol and listening address.
        list($scheme, $address,$port) = explode(':', $this->_socketName, 3);
        if (!isset(self::$_builtinTransports[$scheme])) {
            exit('不支持的网络协议');
        }
        self::$socketName = $this->_socketName;
        $this->server = new self::$_builtinTransports[$scheme](substr($address,2), $port);
        $this->set['log_file'] = self::$logFile;
        $this->set['pid_file'] = self::$pidFile;
        $this->set['daemonize'] = self::$daemonize;
        $this->set['worker_num'] = self::$count;
        if (empty($set)) {
            $set["enable_reuse_port"] = true;
        }
        $this->set = array_merge($this->set, $set);
        $this->server->set($this->set);
        $this->server->on('start', array($this, 'onMasterStart'));
        $this->server->on('managerstart', array($this, 'onManagerStart'));
        $this->server->on('workerstart', array($this, 'onWorkerStart'));
        $this->server->on('shutdown', array($this, 'onShutDown'));
    }
    public function onWorkerStart($serv)
    {
        $this->installSignal();
        self::$serv = $serv;
        if (false === @file_put_contents(self::$pidFile, "\n" . $serv->worker_pid, FILE_APPEND)) {
            throw new Exception('can not save pid to ' . self::$pidFile);
        }
        swoole_set_process_name("Swoole: worker process " . self::$name . " start_file=" . self::$_startFile);
        $this->connectRegister();
        call_user_func([$this,$this->onWorkerStart],$serv);
    }
    public function connectRegister()
    {
        $client = new Swoole\Client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
        //设置事件回调函数
        $client->on("connect", function($cli) {
            $cli->send("hello world\n");
        });
        $client->on("receive", function($cli, $data){
            echo "Received: ".$data."\n";
        });
        $client->on("error", function($cli){
            throw new \Swoole\Exception('连接错误');
        });
        $client->on("close", function($cli){
            echo "Connection close\n";
        });
        //发起网络连接
        list($address,$port) = explode(':', $this->register_address,2);
        $client->connect($address, $port, 0.5);
    }

}